
# JWT_RESPONSE_PAYLOAD_HANDLER
import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    #token 就是jwt生成的Token
    # user 就是认证之后的user

    return {
        'token': token,
        'username': user.username,
        'user_id':user.id
    }


# 登录第一种方式
from django.contrib.auth.backends import ModelBackend

# 代码抽取
def get_user(username):
    try:

        if re.match('1[3-9]\d{9}', username):
            # 手机号
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)

    except User.DoesNotExist:
        return None

    else:
        return user


class UsernameMobileModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        #1.如果用户输入的是用户名根据用户名查询
        #2.如果用户输入的是用手机号根据用户名查询
        # 根据username 的输入格式来判断，如果是手机号格式，就认为是手机号
        #否则就是用户名


        user = get_user(username)

        if user is not None and user.check_password(password):
            return user

# 登录第二种方式


class SettingsBackend(object):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """
    def authenticate(self, request, username=None, password=None, **kwargs):

        #1.如果用户输入的是用户名根据用户名查询
        #2.如果用户输入的是用手机号根据用户名查询
        # 根据username 的输入格式来判断，如果是手机号格式，就认为是手机号
        #否则就是用户名
        try:

            if re.match('1[3-9]\d{9}',username):
                #手机号
                user = User.objects.get(mobile  = username)
            else:
                user = User.objects.get(username = username)

        except User.DoesNotExist:
            return None

        if user.check_password(password):
            return user
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None





